'use strict';
const Controller = require('egg').Controller;
module.exports = app => {
    let store = app.getStore();
    let mongo = app.mongo;
    return class HomeController extends Controller {
        async getSmsCode() {
            let ctx = this.ctx;
            let app = this.app;
            let {
                phone
            } = {
                ...ctx.query,
                ...ctx.request.body
            }
            let url = '/sms/addSms';
            let resultSet = await app.fetch(url, {
                phone
            });
            let res = resultSet.data;
            if (res.code == 0) {
                ctx.body = {
                    code: 0,
                    msg: 'success',
                    phone: String(res.phone).slice(-4)
                }
            } else {
                ctx.body = {
                    code: 1,
                    msg: res.msg
                }
            };
        }

        async add() {
            let ctx = this.ctx;
            // 同时支持get和post请求
            const params = ctx.params;
            let username = params.username;
            let result = await mongo.find('users', {
                query: {
                    username
                }
            });
            // 手机号码不能为空
            if (!username) {
                ctx.body = {
                    code: 1,
                    success: '用户名不能为空',
                }
                return false;
            }
            // 检查用户是否已注册
            if (result.length>0) {
                ctx.body = {
                    code: 0,
                    success: '注册成功'
                }
                return false;
            }
            // 新注册
            const data = await mongo.insertOne('users', {
                doc: params
            });
            if (data.result.n > 0) {
                ctx.body = {
                    code: 0,
                    success: '注册成功',
                    user: params
                }
            } else {
                ctx.body = {
                    code: 1,
                    msg: 'fail'
                }
            }

        }

        async allUser() {
            const data = await mongo.find('users');
            this.ctx.body = {
                code: 0,
                msg: 'success',
                users: data
            }
        }

        async logout() {
            const {
                token
            } = {
                ...this.ctx.request.body,
                ...this.ctx.query
            };
            if (!token) {
                this.ctx.body = {
                    code: 1,
                    msg: 'token不存在'
                };
            } else {
                // 销毁token
                store.destroy({
                    token
                });
                this.ctx.body = {
                    code: 0,
                    msg: '登出成功'
                };
            }

        }

        async login() {
            let {app,ctx} = this;
            const {
                username,
                // wx.login的code
                code,
                // 验证码
                smsCode
            } = ctx.params;
            // 三个参数都不能少
            if (!username) {
                ctx.body = {
                    code: 1,
                    msg: '缺少username'
                };
                return false;
            } 
            if (!code) {
                ctx.body = {
                    code: 1,
                    msg: '缺少code'
                };
                return false;
            } 
            if (!smsCode) {
                ctx.body = {
                    code: 1,
                    msg: '缺少smsCode'
                };
                return false;
            }
            
            // 校验验证码
            const checkResult = await app.fetch('/sms/querySms',{
                username,
                code,
                smsCode
            });
            let res = checkResult.data;
            // 暂不检查验证码
            res.code = 0;
            if (res.code !== 0) {
                ctx.body = {
                    code: 1,
                    msg: res.msg
                }
                return false;
            } 

            let user;
            // 判断用户是否已经登录
            let userinfo = store.get({
                username
            });
            if (userinfo.status == 1) {
                user = userinfo.user;
                let loginTime = new Date();
                store.update({
                    ...user,
                    loginTime
                });
                ctx.body = {
                    code: 0,
                    msg: '登录成功',
                    data: {
                        token: user.token,
                        loginTime: app.utils.formatDate(loginTime),
                        maxAge: user.maxAge
                    }
                }
                return false;
            }


            // 根据传进来的参数进行查询
            const data = await mongo.find('users', {
                query: {
                    username
                }
            });
            if (data.length === 0) {
                this.ctx.body = {
                    code: 1,
                    msg: "用户不存在"
                }
                return false;
            }
            user = data[0];
            if (data.length > 0) {
                let loginTime = new Date();
                // 过期时间30秒
                let maxAge = 10*1000;// 30*60*1000;
                store.set({
                    username: ctx.params.username,
                    token: user._id.toJSON(),
                    loginTime,
                    maxAge
                });
                this.ctx.body = {
                    code: 0,
                    msg: '登录成功',
                    data: {
                        token: user._id.toJSON(),
                        loginTime: app.utils.formatDate(loginTime),
                        maxAge
                    }
                }
            } else {
                this.ctx.body = {
                    code: 1,
                    msg: '登录失败'
                }
            }
        }

        // 获取个人信息
        async getUserInfo() {
            const res = await this.ctx.service.user.getUserInfo();
            if (res.code === 0) {
                this.ctx.body = res;
            } else {
                this.ctx.body = {
                    code: 1,
                    msg: res.msg
                }
            }
        }
    }
}